import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Server } from '../entities/server.entity';
import { ServerMetric } from '../entities/server-metric.entity';
import { Project } from '../entities/project.entity';
import { ProjectMetric } from '../entities/project-metric.entity';
import { Alert } from '../entities/alert.entity';

@Injectable()
export class DashboardService {
  constructor(
    @InjectRepository(Server)
    private serverRepository: Repository<Server>,
    
    @InjectRepository(ServerMetric)
    private serverMetricRepository: Repository<ServerMetric>,
    
    @InjectRepository(Project)
    private projectRepository: Repository<Project>,
    
    @InjectRepository(ProjectMetric)
    private projectMetricRepository: Repository<ProjectMetric>,
    
    @InjectRepository(Alert)
    private alertRepository: Repository<Alert>,
  ) {}

  async getHealthScore(): Promise<number> {
    // 计算整体健康分数
    const servers = await this.serverRepository.find();
    const alerts = await this.alertRepository.find({ where: { status: 'pending' } });
    
    if (servers.length === 0) return 100;
    
    // 计算在线服务器比例
    const onlineServers = servers.filter(server => server.status === 'online').length;
    const serverHealth = (onlineServers / servers.length) * 100;
    
    // 计算告警影响 (假设每个未处理告警扣2分)
    const alertDeduction = Math.min(alerts.length * 2, 100);
    
    // 综合健康分数
    return Math.max(0, serverHealth - alertDeduction);
  }

  async getKpiMetrics(): Promise<any> {
    // 获取关键性能指标
    const serverCount = await this.serverRepository.count();
    const projectCount = await this.projectRepository.count();
    const alertCount = await this.alertRepository.count({ where: { status: 'pending' } });
    
    // 获取最近的服务器指标
    const latestMetrics = await this.serverMetricRepository.find({
      order: { collectedAt: 'DESC' },
      take: 5,
    });
    
    const avgCpuUsage = latestMetrics.length > 0 
      ? latestMetrics.reduce((sum, metric) => sum + metric.cpuUsage, 0) / latestMetrics.length 
      : 0;
      
    const avgMemoryUsage = latestMetrics.length > 0 
      ? latestMetrics.reduce((sum, metric) => sum + metric.memoryUsage, 0) / latestMetrics.length 
      : 0;
    
    return {
      serverCount,
      projectCount,
      alertCount,
      avgCpuUsage: parseFloat(avgCpuUsage.toFixed(2)),
      avgMemoryUsage: parseFloat(avgMemoryUsage.toFixed(2)),
    };
  }

  async getHeatmapData(): Promise<any[]> {
    // 获取热力图数据
    const servers = await this.serverRepository.find({ relations: ['metrics'] });
    
    return servers.map(server => ({
      serverName: server.serverName,
      location: server.location,
      status: server.status,
      cpuUsage: server.metrics.length > 0 
        ? server.metrics[server.metrics.length - 1].cpuUsage 
        : 0,
      memoryUsage: server.metrics.length > 0 
        ? server.metrics[server.metrics.length - 1].memoryUsage 
        : 0,
    }));
  }
}